package com.dzy.chiyan.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dzy.chiyan.R
import com.dzy.chiyan.adapter.MessageAdapter
import com.dzy.chiyan.data.DBHelper
import com.dzy.chiyan.data.Message
import com.dzy.chiyan.data.MessageDAOImpl
import com.dzy.chiyan.data.UserInfoDaoImpl
// 聊天
class ChatActivity : BaseActivity() {

    private lateinit var messageAdapter: MessageAdapter
    private lateinit var messageRecyclerView: RecyclerView
    private var currentUserId = 0
    private var chatPartnerId = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)
        // 初始化用户 ID
        currentUserId = intent.getIntExtra("userID", 0)
        chatPartnerId = intent.getIntExtra("friendId", 0)
        Log.d("ChatActivity", "currentUserId: $currentUserId, chatPartnerId: $chatPartnerId")
        // 设置联系人名称
        val userInfoDao = UserInfoDaoImpl(DBHelper(this))
        val contactNameView = findViewById<TextView>(R.id.text_contact_people)
        contactNameView.text = userInfoDao.getUser(chatPartnerId)?.nickname
        // 获取当前用户和聊天对象的昵称
        val currentUserName = userInfoDao.getUser(currentUserId)?.nickname ?: "Unknown User"
        val chatPartnerName = userInfoDao.getUser(chatPartnerId)?.nickname ?: "Unknown Partner"
        messageRecyclerView = findViewById(R.id.recyclerView_messages)
        messageRecyclerView.layoutManager = LinearLayoutManager(this)
        // 创建适配器实例
        messageAdapter = MessageAdapter(mutableListOf(), currentUserId, currentUserName, chatPartnerName)
        messageRecyclerView.adapter = messageAdapter
        // 加载历史消息
        loadChatMessages()
    }

    private fun loadChatMessages() {
        val messageDao = MessageDAOImpl(DBHelper(this))
        val chatMessages = messageDao.getMessagesBySenderReceiver(currentUserId, chatPartnerId)
        messageAdapter.reloadData(chatMessages)
        // 滚动到最新消息
        scrollToBottom()
    }

    fun onBackButtonClick(view: View) {
        finish()
    }

    fun onSendMessageButtonClick(view: View) {
        val messageInputView = findViewById<TextView>(R.id.edit_message)
        // 获取用户输入的消息内容并去除前后空格
        val messageContent = messageInputView.text.toString().trim()
        messageInputView.text = ""
        // 如果消息内容不为空，发送
        if (messageContent.isNotEmpty()) {
            //消息的发送时间
            val sentAtTimestamp = (System.currentTimeMillis() / 1000).toString()
            val newMessage = Message(0, currentUserId, chatPartnerId, messageContent, sentAtTimestamp)
            val messageDao = MessageDAOImpl(DBHelper(this))
            // 尝试将新消息插入数据库
            if (messageDao.insertMessage(newMessage)) {
                messageAdapter.addMessage(newMessage)
                scrollToBottom()
            }
        }
    }

    private fun scrollToBottom() {
        messageRecyclerView.smoothScrollToPosition(messageAdapter.itemCount - 1)
    }
}
